/*
 * $Header: /opt/javacvs/util/src/main/java/com/uusee/util/PropertiesUtil.java,v 1.2 2008/04/03 04:53:23 duy Exp $
 * $Revision: 1.2 $
 * $Date: 2008/04/03 04:53:23 $
 * ============================================================================
 *
 * Copyright (c) 2008 Beijing uusee Tech CO.,  All rights reserved.
 *
 * ============================================================================
 */
package com.uusee.util;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * properties属性配置文件处理工具类
 * 
 * @author duyi
 * 
 * Create Time: 2008-2-28 下午04:07:37
 */
public class PropertiesUtil {
	private static Log log = LogFactory.getLog(PropertiesUtil.class);
	// 缺省的资源文件名字
	private static final String CONFIG = "system";
	// 参数标记:{0}{18}
	private static final String PARAMETER_FLAG = "\\{\\d+\\}";

	/**
	 * 从CONFIG文件中取键为key的值
	 * 
	 * @param key
	 * @return
	 */
	public static String getString(String key) {
		return getString(CONFIG, key);
	}

	/**
	 * 从resourceFile文件中取键为key的值
	 * 
	 * @param resourceFile
	 * @param key
	 * @return
	 */
	public static String getString(String resourceFile, String key) {
		return getString(resourceFile, key, null);
	}

	/**
	 * 从CONFIG文件中取键为key的值,并填充参数
	 * 
	 * @param key
	 * @param parameters
	 * @return
	 */
	public static String getString(String key, String[] parameters) {
		return getString(CONFIG, key, parameters);
	}

	/**
	 * 从resourceFile文件中取键为key的值,并填充参数
	 * 
	 * @param resourceFile
	 * @param key
	 * @param parameters
	 * @return
	 */
	public static String getString(String resourceFile, String key,
			String[] parameters) {
		String result = null;
		try {
			result = ResourceBundle.getBundle(resourceFile).getString(key);
		} catch (MissingResourceException e) {
			if (log.isErrorEnabled()) {
				log.error(e.getMessage());
				log.error("无法获得" + resourceFile + ".properties文件中的" + key
						+ "属性");
			}
		}
		if (ArrayUtil.isNotEmpty(parameters)) {
			result = fillParameterToValue(result, parameters);
		}
		if (log.isDebugEnabled()) {
			log.debug("取得值: [" + result + "]");
		}
		return result;
	}

	/*
	 * 填充参数值方法
	 */
	private static String fillParameterToValue(String value, String[] parameters) {
		for (int i = 0; i < parameters.length; i++) {
			value = value.replaceFirst(PARAMETER_FLAG, parameters[i]);
		}
		return value;
	}
}
